const boardModel = require("../model/boardModel")
const eventModel = require("../model/eventModel")
const eventBoardModel = require("../model/eventBoardModel")
const userModel = require("../model/userModel")
const userEventModel = require("../model/userEventModel")

//创建投票事件
const createEvent = async (req,res,next) => {
  try{
    const {host,describe,startTime,endTime,boardList,userAddressList} = req.body;
    //1.创建选举事件
    const event_id = await eventModel.addEvent(host,describe,new Date(),startTime,endTime);
    //2.创建选举人并关联事件
    await boardList.forEach(async (board) => {
      const board_id = await boardModel.addBoard(board.name);
      await eventBoardModel.addEventBoard(event_id,board_id);
    });
    //3.加入投票人 关联事件
    await userAddressList.forEach(async (address) => {
      const user_id = await userModel.getUserIdByAddress(address);
      await userEventModel.addUserToEvent(user_id,event_id);
    });

    //返回
    res.send({
      code: "200",
      msg: "投票事件创建成功!"
    })
  } catch (error) {
    next(error)
  }
}

//获取所有投票事件列表
const getAllEvents = async (req,res,next) => {
  try{
    const eventList = await eventModel.getAllEvents();
    if(eventList){
      res.send({
        code: "200",
        msg: "获取投票事件列表成功!",
        data:eventList
      })
    }else{
      res.send({
        code: "403",
        msg: "获取投票事件列表失败!"
      })
    }
  } catch (error){
    next(error)
  }
}


module.exports = {createEvent, getAllEvents}